package cn.mily.org.controller;

import cn.mily.basics.utils.JsonResult;
import cn.mily.basics.utils.PageBean;
import cn.mily.org.domain.Product;
import cn.mily.org.query.ProductQuery;
import cn.mily.org.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService service;



    /*====↑门户网站接口↑============================↓前端后台接口↓===================================================*/

    @PutMapping/*添加*/
    public JsonResult add(@RequestBody Product product){
        try {
            if(product.getId()==null)/*判断是否拥有id  有为修改没有为添加*/
                service.add(product);
            else/*有id修改*/
                service.update(product);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("添加失败！");
        }
    }

    @PatchMapping("/on")/*批量上架*/
    public JsonResult pachOn(@RequestBody Long[] ids){/*根据id数组批量上架*/
        try {
            service.patchOn(ids);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("删除失败！");
        }
    }

    @PatchMapping("/off")/*批量下架*/
    public JsonResult pachOff(@RequestBody Long[] ids){/*根据id数组批量下架*/
        try {
            service.patchOff(ids);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("删除失败！");
        }
    }

    @PatchMapping/*批量删除*/
    public JsonResult pachDelete(@RequestBody Long[] ids){/*根据id数组批量删除*/
        try {
            service.patchDelete(ids);
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("删除失败！");
        }
    }


    @DeleteMapping("/{id}")/*删除*/
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            service.delete(id);/*根据id删除*/
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("添加失败！");
        }
    }

    @GetMapping("/{id}")/*根据id获取*/
    public Product findOne(@PathVariable("id") Long id){
        return service.findOne(id);/*查询单个，根据id查询*/
    }

    @PostMapping/*获取全部*/
    public PageBean<Product> findAll(@RequestBody ProductQuery query){
        return service.findAll(query);
    }

}
